﻿using System;
using System.Collections.Generic;
using System.Text;

using WFL.Threading;

namespace WFL.Data
{
    public class EntityDefinitionManager
    {
        private Dictionary<Type, EntityDefinition> _entities = new Dictionary<Type, EntityDefinition>();
        private WriteReadObjectLock _lock = new WriteReadObjectLock();

        public string Provider
        {
            get;
            private set;
        }

        public EntityDefinitionManager(string provider)
        {
            if (string.IsNullOrEmpty(provider))
            {
                throw new ArgumentNullException("provider");
            }
            Provider = provider;
        }

        public EntityDefinition Get<T>()
        {
            return Get(typeof(T));
        }

        public EntityDefinition Get(Type type)
        {
            _lock.AcquireRead();
            EntityDefinition item = null;
            try
            {
                if (_entities.ContainsKey(type))
                {
                    item = _entities[type];
                }
            }
            finally
            {
                _lock.ReleaseRead();
            }
            if (item == null)
            {
                _lock.AcquireWrite();
                try
                {
                    if (_entities.ContainsKey(type))
                    {
                        item = _entities[type];
                    }
                    else
                    {
                        item = EntityDefinition.Create(type, Provider, this);
                        _entities.Add(item.Type, item);
                    }
                }
                finally
                {
                    _lock.ReleaseWrite();
                }
            }
            return item;
        }
    }
}
